package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpSession;

@Controller
@RequestMapping("/")
public class HomeController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ScreeningService screeningService;
    
    
    @Autowired
    private SnackService snackService;
    
    @Autowired
    private ScreeningRoomService screeningRoomService;
    
    @GetMapping
    public String home(Model model, HttpSession session) {
        String username = (String) session.getAttribute("username");
        String role = (String) session.getAttribute("role");
        
        if (username != null) {
            model.addAttribute("username", username);
            model.addAttribute("role", role);
            
            // 添加统计信息
            model.addAttribute("totalMovies", movieService.getTotalMovieCount());
            model.addAttribute("totalRooms", screeningRoomService.getTotalRoomCount());
            model.addAttribute("totalSeats", screeningRoomService.getTotalSeats());
            model.addAttribute("availableSnacks", snackService.getAvailableSnacksCount());
            
            // 获取今日场次
            model.addAttribute("todayScreenings", screeningService.getTodayScreenings());
            
            // 添加当前用户对象到模型中
            if (username != null) {
                model.addAttribute("currentUser", userService.getUserByUsername(username).orElse(null));
            }
            
            switch (role) {
                case "admin":
                    return "admin/dashboard";
                case "manager":
                    return "manager/dashboard";
                case "receptionist":
                    return "receptionist/dashboard";
                default:
                    return "user/dashboard";
            }
        }
        
        return "login";
    }
    
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    
    @GetMapping("/register")
    public String register() {
        return "register";
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}